package com.robot.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
public class CorsFilter implements Filter {
//
//    public void doFilter(ServletRequest req, ServletResponse res,
//                         FilterChain chain) throws IOException, ServletException {
//        log.info("res...........:{}", res.toString());
//        HttpServletResponse response = (HttpServletResponse) res;
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
////        response.setHeader("Access-Control-Max-Age", "3600");
//        response.setHeader("Access-Control-Allow-Headers", "*");
//
//
//
//        log.info("response..................:{}", response.toString());
//        chain.doFilter(req, res);
//
//
//    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        log.info("res...........:{}", request.toString());
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        // 设置CORS相关的响应头
        res.setHeader("Access-Control-Allow-Origin", "http://121.199.66.169:8000"); // 或者指定具体的域，例如 "http://example.com"
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        res.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");
        // 如果需要允许携带凭证信息
        res.setHeader("Access-Control-Allow-Credentials", "true");
        log.info("response..................:{}", response.toString());
        // 对于预检请求（OPTIONS），直接返回成功响应，不继续执行链中的其他过滤器或目标资源
        if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
            res.setStatus(HttpServletResponse.SC_OK);
        } else {
            // 否则，继续执行链中的其他过滤器或目标资源
            chain.doFilter(request, response);
        }

    }
    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}